import{comments} from "../../../js/modules/mall.js" 
import {router} from '../../../js/router'; 
import BasePage from '../../../js/common/base-page' 
import {api,util} from '../../../js/util'
import {config} from '../../../js/modules/gloab'
import authorize from '../../../js/modules/authorize'
var app = getApp();
BasePage({
  // pageKey: "find", 
  // validateLogin: app.dns.fkId != app.dns.proprietorId,
  validateLogin: false,
  /**
   * 页面的初始数据
   */
  data: {
    enableOss: api.enableOss,
    imgDomain: api.imgDomain,
    videoDomain:api.videoDomain,
    activeIndex: 0,
    activeTab: 0,
    videoList:[],
    _index:0,//当前正在播放视频的数组下标
    PageIndex:1,
    PageSize:10,
    hasMoreData:true,
    navList:[{Id:3,Name:'资讯'}],//选项卡列表
    sectionIndex:1,
    currentType:'',//
    tabs:[],//选项卡
    detail_show: '',
    hasFooter:false, //是否有底部导航
    searchVal:'',//搜索
    pagenationObj: {},
    headerBg:'',//背景图
    isIphoneX:app.globalData.isIphoneX,
    thumbWidth:800,
    thumbHeight:800,
    fitHeight:750,
    searchBox:false,//搜索
    findSort:0,//排序
    MeansList:[],//资料列表
    ParentIndex:0,//父子级
    crumbsTxt:'',//面包屑
    arrName:[],
    crumbsID:[],
    tabindex:-1,
    iconImg:api.host+'/WebSupplier/Template/Default/Css/skin/Default/images/icon/',
    meansType:'',
    meansUrl:'',
    modelBox:false,
    filePath:'',
    isLoadComplete: false, // 是否已加载数据
    preventGetData: false, // 是否阻止加载数据（当没有开启的版块时，不应该加载数据）
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //隐藏原生底部导航
    app.initTabBar();
    // 获取配置，是否需要登录才能查看这个页面
    this.getWholesaleConfig()
    //选项卡
    this.navList();
    //判断是否装修了商品导航，如果装修了，则显示底部
    let hasGoods = app.globalData.tabBar.list.filter((item)=>item.text=='发现');
    if(hasGoods.length!=0){
      this.setData({
        hasFooter:true
      },function(){
        app.initTabBar();
      })
    }	
  },
  /**
   * 获取配置信息
   */
  getWholesaleConfig() {
    var that = this;
    var fkid = app.dns.proprietorId;
    var fkflag = app.dns.proprietor;
    config.getWholesaleConfigs(
      fkid,
      fkflag,
      "Wholesale",
      function(model) {
        if (model.NoLoginShowInteraction == false) {
          if (!authorize.isLogin('store')) {
            authorize.redirect('store')
            return
          }
        }
      });
  },
  /**
  * 搜索
  */
  bindSearch:function(){
    this.setData({
      searchBox:true
    })
  },
  bindBack:function(){
    this.setData({
      searchBox:false
    })
  },
  iptSearch:function(e){
    this.setData({
      searchVal:e.detail.value
    })
  },
  btnSearch:function(){
    var that = this;
    if(that.data.findSort == -3){
      that.setData({
        searchBox:false
      })
      that.getMeansList();
    }else{
      that.setData({
        PageIndex: 1,
        videoList:[],
        searchBox:false,
        isLoadComplete: false
      })
      that.getDataList();
    }
  },
  /**
  * 列表
  */
  getDataList:function(){
    var that = this;
    let data = {
      SectionId: that.data.sectionIndex == 1 ? 0 : that.data.currentType ? that.data.currentType : that.data.activeIndex,
      PageIndex: that.data.PageIndex,
      PageSize: that.data.PageSize,
      keyword: that.data.searchVal
    }
    if (that.data.preventGetData) {
      that.setData({
        hasMoreData: false,
        isLoadComplete: true
      })
      return
    }
    comments.getCommunityList(data,function(content){
      if(content.Success){
        let hasMore = content.Content.count > that.data.PageIndex * that.data.PageSize;
        var data = content.Content.data;
        data.forEach(function(item){
          
          item.num = 2;
          item.open = false;
          if(item.Image.indexOf(',') === -1){
            item.Image = item.Image;
          }else{
            item.Image = item.Image.split(',')[0];
          }
          item.PublishTime = util.getDateSt(item.PublishTime,0,'date');
        })
        //当分页大于1时，累加
        if (that.data.PageIndex > 1) {
          data = that.data.videoList.concat(data);
        }
        that.setData({
          videoList:data,
          pagenationObj: {
            count: content.Content.count,
            pageIndex: that.data.PageIndex,
            pageSize: that.data.PageSize
          },
          hasMoreData: hasMore,
          isLoadComplete: true
        })
      } else {
        that.setData({
          isLoadComplete: true
        })
      }
    })
  },
  /**
  * 选项卡
  */
  navList:function(){ 
    var that = this;
    comments.getNavList(function(content){
      let first_tab = content.Content.find((item) => item.Reorder === -1);
      let copy_firstTab = [].concat(that.data.navList);
      if (first_tab) {
        copy_firstTab.unshift({ Id:2, Name: first_tab.Name,type:first_tab.Id});
      }
      copy_firstTab.sort((a,b)=>a.Id-b.Id)
      let list = content.Content.filter((item) => item.Reorder !== -1);
      console.log('copy_firstTab',list)
      let preventGetData = false
      if (content.Content.length == 0) {
        preventGetData = true
      }
      that.setData({
        tabs:list,
        activeIndex:list.length == 0?0:list[0].Id,
        findSort:list.length == 0?0:list[0].Reorder,
        navList:copy_firstTab,
        sectionIndex:copy_firstTab[0].Id,
        currentType:copy_firstTab.length==0?0:copy_firstTab[0].type,
        preventGetData
      },function(){
        that.getDataList();
        try {
          if( copy_firstTab[0].Id == 3 && list[0].Reorder == -3){
            //资料列表
            that.getMeansList();
          }
        } catch (error) {
          console.log(error)
        }
      })
    })
  },
  //资料列表
  getMeansList:function(){
    var that = this;
    var data = {ParentId:that.data.ParentIndex,keyword:that.data.searchVal};
    if (that.data.preventGetData) {
      return
    }
    comments.getListFormoment(data,function(content){
      that.setData({
        MeansList:content
      })
    })
  },
  //下载资料
  bindFlie(e){
    var that = this;
    var arrName = that.data.arrName;
    var arrID = that.data.crumbsID;
    var url = e.currentTarget.dataset.url;
    var type = e.currentTarget.dataset.type;
    var id = e.currentTarget.dataset.id;
    var name = e.currentTarget.dataset.name;
    var types = e.currentTarget.dataset.types;
    this.setData({
      meansType:type,
      meansUrl:that.data.imgDomain+url
    })
    if(type && types == 'File'){
      if(!url)return;
      if(type=='jpeg'||type=='jpg'||type=='png'||type=='bmp'||type=='gif'||type=='ico'||type == 'mp3'||type == 'mp4'){
        this.setData({
          modelBox:true
        })
      }else{
        that.uploadFile()
      }
    }else{
      wx.navigateTo({
        url: '/packageCommunity/pages/file/index?id='+id+'&keyword='+that.data.searchVal+'&name='+name,
      })
    }
  },
  uploadFile(){
    var that=this;
    var url = that.data.meansUrl
    var type = that.data.meansType
    console.log(url,'===');
    wx.showModal({
      title: '温馨提示',
      content: '是否确认是想要下载文件',
      success (res) {
        if (res.confirm) {
          wx.showLoading({title:'下载中'})
          wx.downloadFile({ 
            url: url.replace("http://", "https://"), //仅为示例，并非真实的资源
            success (res) {
              that.setData({
                filePath:res.tempFilePath
              })
              // 只要服务器有响应数据，就会把响应内容写入文件并进入 success 回调，业务需要自行判断是否下载到了想要的内容
              if (res.statusCode === 200) {
                if(type=='jpeg'||type=='jpg'||type=='png'||type=='bmp'||type=='gif'||type=='ico'){
                  wx.saveImageToPhotosAlbum({
                    filePath: that.data.filePath,
                    success(res) {
                      wx.hideLoading()
                      wx.showModal({
                        content:'图片已下载到相册',
                        showCancel:false,
                        confirmText:'好的',
                        confirmColor:'#333',
                        success:function(res){},
                        fail:function(res){}
                      })
                    },
                    fail: function (res) {
                      wx.showToast({
                        title:"下载失败",
                        icon:'none',
                        duration:2000
                      })
                    }
                  })
                }else if(type=="mp4" || type=="mp3"){
                  wx.setClipboardData({
                    data:url.replace("http://", "https://"),
                    success (res) {
                      wx.hideLoading();
                      util.tips('复制成功，请在浏览器中进行下载');
                    }
                  })
                }else{
                  wx.openDocument({
                    filePath:that.data.filePath,
                    success:function(res){wx.hideLoading()}
                  })
                }
              }
            }
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  bindCancel(){
    this.setData({
      modelBox:false
    })
  },
  onTabCLick(e) {
    const index = e.detail.index;
    const id = e.detail.id;
    const sort = e.detail.sort;
    if(this.data.activeTab == index)return;
    this.setData({
      activeIndex: id,
      findSort:sort,
      videoList:[],
      pagenationObj: {
        count: 0,
        pageIndex: 1,
        pageSize: this.data.PageSize
      },
      activeTab:index,
      hasMoreData:true,
      PageIndex: 1,
      // searchVal:''
    });
    if(sort == -3){
      //资料列表
      this.getMeansList();
    }else{
      //列表
      this.getDataList();
    }
    
  },

  btnSection:function(e){
    var that = this;
    var id = e.currentTarget.dataset.id;
    var type = e.currentTarget.dataset.type;
    var tabs = that.data.tabs;
    if(that.data.sectionIndex == id)return;
    that.setData({
      sectionIndex:id,
      PageIndex: 1,
      currentType:type,
      isLoadComplete: false,
      // searchVal:''
    })
    if(tabs.length > 0){
      if(id == 3 && tabs[0].Reorder == -3){
        //资料列表
        that.getMeansList();
      }
    }
    //列表
    that.getDataList();
  },
 
  /**
   * 发布
  */
  btnRelease:function(){
    wx.navigateTo({
      url: '/packageCommunity/pages/releaseImg/index?type=1',
    })
    // if (this.data.detail_show == 'open') {
    //   this.setData({
    //     detail_show: ''
    //   })
    // } else {
    //   this.setData({
    //     detail_show: 'open'
    //   })
    // }
  },
  /**
   * 我的发现 
  */
  btnFind:function(){
    wx.navigateTo({
      url: '/packageCommunity/pages/userFind/index'
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    wx.hideHomeButton();
    var tabindex = app.getTabBarindex();
    this.setData({
      tabindex:tabindex
    })
    this.setData({
      headerBg: api.titleColor||"#e56b14"
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    if (this.data.detail_show == 'open') {
      this.setData({
        detail_show: ''
      })
    }
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.setData({
      PageIndex: 1,
      videoList: [],
      isLoadComplete: false,
    })
    this.getDataList();
    wx.stopPullDownRefresh(); 
    
    // console.log('========刷新');
  },

  /**
  * 页面上拉触底事件的处理函数
  */
  onReachBottom: function () {
    // console.log(this.data.hasMoreData,'-----false');
    if (this.data.hasMoreData) {
      var index = this.data.PageIndex;
      this.setData({
        PageIndex:index+1
      },function(){
        this.getDataList();
      })
    }
  },
  bindList:function(e){
    var id = e.currentTarget.dataset.id;
    var type = e.currentTarget.dataset.type;
    var video = e.currentTarget.dataset.video; 
    if(type == 1){//公告
      router.navigate({
        path: "notDetail",
        params: {id: id}
      })
    }else if(video){//视频
      router.navigate({
        path: "videoDetail",
        params: {id: id}
      })
    }else{//文章
      router.navigate({
        path: "postdetail",
        params: {id: id}
      })
    }
  },

  loadVideoListEvent(e) {
    if(e.detail){
      if (this.data.hasMoreData) {
        var index = this.data.PageIndex;
        this.setData({
          PageIndex:index+1
        },function(){
          this.getDataList();
        })
      }
    }
  },
  /**
  * 页面滚动触发
  */
   /**
  * 生命周期函数--监听页面初次渲染完成
  */
  onReady: function () {
    // this.myComponent = this.selectComponent('#myComponent').scrollList();
  },
  /**
  * 生命周期函数--监听页面卸载
  */
  onUnload: function () {
    
  },
  /**
 * 用户点击右上角分享
 */
  onShareAppMessage: function () {
    
  },
  bindLike(e){
    var that = this;
    var id =  e.currentTarget.dataset.id;
    var status = e.currentTarget.dataset.status;// true - false
    var data = {Type:0,Id:id};
    var list = this.data.videoList;
    // 登录后才能点赞
    if (!authorize.isLogin('store')) {
      authorize.redirect('store')
      return
    }
    if(!status){
      //点赞
      comments.getUserFollow(data,function(content){
        if(content.Success){
          for(var i=0;i<list.length;i++){
            if(list[i].Id == id){
              list[i].IsSupport = !list[i].IsSupport;
              list[i].LikeCount ++;
            }
          }
          that.setData({
            videoList:list
          })
        }else{
          util.alert(content.Message);
        }
      })
    }else{
      //取消点赞
      comments.getUserCancel(data,function(content) {
        if(content.Success){
          for(var i=0;i<list.length;i++){
            if(list[i].Id == id){
              list[i].IsSupport = !list[i].IsSupport;
              list[i].LikeCount --;
            }
          }
          that.setData({
            videoList:list
          })
        }else{
          util.alert(content.Message);
        }
      })
    }
  },
})
